package com.jy.datapipeline.common.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.jy.datapipeline.export.entity.DataSourceInfoModel;
import com.jy.datapipeline.export.service.DataSourceInfoService;
import com.jy.datapipeline.common.util.TEAUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;

import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;

@Configuration
@Slf4j
public class  DBMetaDataConfig {

    @Value("${config.threadCorePoolSize}")
    private int threadCorePoolSize;

    @Value("${config.threadMaxPoolSize}")
    private int threadMaxPoolSize;

    @Value("${config.druidInitSize}")
    private int druidInitSize;

    //private  static Map<String,DruidDataSource> druidDataSourceMap=new HashMap<>();

    @Autowired
    private DataSourceInfoService dataSourceInfoService;

    public   static Map<String,DruidDataSource> dataSourceMap=new HashMap<>();



    public void refreshDataSource(DataSourceInfoModel dsim){
        DruidDataSource ds=DBMetaDataConfig.dataSourceMap.get(dsim.getDataSourceId());
        if(ds==null){
           ds= this.addPassDataSource(dsim);
           DBMetaDataConfig.dataSourceMap.put(dsim.getDataSourceId(),ds);
        }else{
            DBMetaDataConfig.dataSourceMap.put(dsim.getDataSourceId(),this.addPassDataSource(dsim));
        }
    }



    //初始化
    @PostConstruct
    public void initDataSource(){
        List<DataSourceInfoModel> list= this.dataSourceInfoService.findAll();
        if(list.size()>0){
            for(int i=0;i<list.size();i++){
                DataSourceInfoModel dsim=list.get(i);
                DruidDataSource ds= this.addPassDataSource(dsim);
                DBMetaDataConfig.dataSourceMap.put(dsim.getDataSourceId(),ds);
                log.info("init DruidDataSource {}",dsim.getDataSourceName());
            }
        }
    }
    //@Bean("PassDataSource")
    public DruidDataSource addPassDataSource(DataSourceInfoModel dsim){
        DruidDataSource dataSource = new DruidDataSource();
        String password = dsim.getPassword();
        if (!StringUtils.isNullOrEmpty(password)) {
            password = TEAUtil.decode(password);
        }
        dataSource.setUrl(dsim.getJdbcUrl());
        dataSource.setUsername(dsim.getUserName());
        dataSource.setPassword(password);
        dataSource.setDriverClassName("com.jy.client.jdbc.PaasDriver");
        //配置初始化大小、最小、最大
        dataSource.setInitialSize(druidInitSize);
        dataSource.setMinIdle(threadCorePoolSize);
        dataSource.setMaxActive(threadMaxPoolSize);
        dataSource.setValidationQuery("SELECT 1 FROM DUAL");
  //      dataSource.setTestWhileIdle(true);
   //     dataSource.setTestOnBorrow(true);
   //     dataSource.setKeepAlive(true);
//      dataSource.setConnectionErrorRetryAttempts(3);
//      dataSource.setBreakAfterAcquireFailure(true);
//      SpringBeanU
        return  dataSource;
    }


    @Bean("asyncTaskExecute")
    public ThreadPoolTaskExecutor asyncTaskExecute() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize( threadCorePoolSize);
        taskExecutor.setMaxPoolSize(threadMaxPoolSize);
        taskExecutor.setQueueCapacity(threadCorePoolSize*5);
        taskExecutor.setKeepAliveSeconds(60);
        taskExecutor.setThreadNamePrefix("asyncTaskExecute-");
        taskExecutor.setRejectedExecutionHandler(new CallerRunsPolicy());
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        taskExecutor.setAwaitTerminationSeconds(60);
        return taskExecutor;
    }

    @Bean("asyncTask2")
    public ThreadPoolTaskExecutor asyncTask() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(threadCorePoolSize);
        taskExecutor.setMaxPoolSize(threadMaxPoolSize);
        taskExecutor.setQueueCapacity(threadCorePoolSize*5);
        taskExecutor.setKeepAliveSeconds(60);
        taskExecutor.setThreadNamePrefix("asyncTask-");
        taskExecutor.setRejectedExecutionHandler(new CallerRunsPolicy());
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        taskExecutor.setAwaitTerminationSeconds(60);
        return taskExecutor;
    }

//    public static void main(String[] args) {
//       System.out.println( TEAUtil.encode("gWIdX9RyaThdIb7a"));
//    }
//    @Bean
//    public TaskScheduler taskScheduler() {
//        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
//        scheduler.setPoolSize(threadCorePoolSize);
//        scheduler.setThreadNamePrefix("taskScheduler-");
//        scheduler.setRejectedExecutionHandler(new CallerRunsPolicy());
//        scheduler.setWaitForTasksToCompleteOnShutdown(true);
//        scheduler.setAwaitTerminationSeconds(60);
//        return scheduler;
//    }
    @PostConstruct
    public void setProperties(){

        System.setProperty("druid.mysql.usePingMethod","false");
//        SpringBeanUtils.registerBean("jdbcTemplate", JdbcTemplate.class,
//           );
    }

}